<?php
/*
附加组件用基类
*/
class gAddon {
	/**
	 * 对templateCode实施变换
	 * @param string $templateCode		模板编译后的HTML+PHP的代码  
	 * @param array|callback $spells	callback数组或callback，接受QueryPath对象作为参数对其进行一定操作 
	 * @return string
	 */
	static final function cast($templateCode, $spells) {
		require_cache(APP_PATH.'/Lib/QueryPath/QueryPath.php');
		try{
			//make a salt
			$s = sha1(C('SITE_KEY').'casting spells');
			//encode php codes
			$templateCode = preg_replace('/(<\\?.+?\\?>)/e', '"==$s==".base64_encode(\'\\1\')."==$s=="', $templateCode);
			$qp = qp($templateCode);
		} catch(Exception $e) {
			throw_exception($e->getMessage());
			return null;
		}
		//cast spells
		if(is_callable($spells)) {
			call_user_func($spells, $qp);
		} elseif(is_array($spells)) foreach($spells as $spell) {
			if(is_callable($spell)) call_user_func($spell, $qp);
		}
		$templateCode = $qp->top()->html();
		//decode php codes
		$templateCode = preg_replace("/==$s==(.+?)==$s==/e", 'base64_decode(\'\\1\')', $templateCode);
		return $templateCode;
	}

}
?>